package cn.itcast.controller.cargo;


import cn.itcast.base.BaseController;
import cn.itcast.domain.cargo.*;


import cn.itcast.domain.vo.ContractProductVo;
import cn.itcast.service.*;
import cn.itcast.utils.DownloadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletContext;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/cargo/finance")
public class FinanceController extends BaseController {
    @Reference
    private FinanceService financeService;
    @Reference
    private InvoiceService invoiceService;

    @Reference
    private PackingService packingService;

    @Reference
    private ShippingService shippingService;

    @Reference
    private ExportService exportService;

    @Reference
    private ExportProductService exportProductService;

    @Reference
    private ContractProductService contractProductService;


    @RequestMapping(name = "pageHelper插件分页查询财务保运", value = "/list")
    public String findAll(@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "5") int pageSize) {
        FinanceExample financeExample = new FinanceExample();
        PageInfo pb = financeService.findAll(financeExample, pageNum, pageSize);
        request.setAttribute("pb", pb);
        return "cargo/finance/finance-list";
    }

    @RequestMapping(name = "查看报运单", value = "/findById")
    public String findById(String id) {
        Finance finance = financeService.findById(id);
        request.setAttribute("finance", finance);
        return "cargo/finance/finance-find";
    }

    @RequestMapping(value = "/toAdd")
    public String toAdd(String id) {
        Invoice invoice = invoiceService.selectById(id);
        Finance finance = new Finance();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(new Date());
        finance.setInputDate(format);
        finance.setInvoiceId(invoice.getInvoiceId());
        finance.setInvoiceMoney(invoice.getInvoiceMoney());
        finance.setExportNos(invoice.getScNo());
        finance.setInvoiceTime(invoice.getInvoiceTime());
        Shipping byId = shippingService.findById(id);
        finance.setShipmentPort(byId.getPortOfLoading());
        finance.setDestinationPort(byId.getPortOfDischarge());
        finance.setConsignee(byId.getShipper());
        request.setAttribute("finance", finance);
        return "cargo/finance/finance-add";
    }

    @RequestMapping(name = "添加", value = "/edit")
    public String edit(Finance finance) {
        Invoice invoice = new Invoice();
        invoice.setInvoiceId(finance.getInvoiceId());
        invoice.setState(1);
        invoiceService.updateInvoice(invoice);
        finance.setFinanceId(UUID.randomUUID().toString());
        financeService.edit(finance);
        return "redirect:/cargo/invoice/list.do";
    }

    @RequestMapping(name = "下载", value = "/printTemplate")
    public void printTemplate(String packingId) throws IOException {
        Finance finance = financeService.findById(packingId);
        Workbook wb = new XSSFWorkbook();
        Sheet st = wb.createSheet();
        st.setColumnWidth(1, 15 * 256);
        st.setColumnWidth(2, 15 * 256);
        st.setColumnWidth(3, 15 * 256);
        st.setColumnWidth(4, 15 * 256);
        st.setColumnWidth(5, 15 * 256);
        st.setColumnWidth(6, 15 * 256);
        st.setColumnWidth(7, 15 * 256);
        st.setColumnWidth(8, 15 * 256);
        st.setColumnWidth(9, 15 * 256);
        int rowIndex = 0; //行数
        Row row;  //行
        Cell cell; //单元
        //第一行
        row = st.createRow(rowIndex++);
        row.setHeightInPoints(36);
        cell = row.createCell(1);
        st.addMergedRegion(new CellRangeAddress(0, 0, 1, 9));
        cell.setCellValue("出口商品报运单");
        CellStyle cellStyle = bigTitle(wb);
        cell.setCellStyle(cellStyle);
        //第二行
        row = st.createRow(rowIndex++);
        String[] arr = {"", "财务报运单ID", "制单时间", "发票号", "发票金额", "发票时间", "报运合同号", "装运港", "目的港", "收货人"};
        for (int i = 1; i < arr.length; i++) {
            cell = row.createCell(i);
            cell.setCellValue(arr[i]);
            CellStyle title = title(wb);
            cell.setCellStyle(title);
        }
        // 设置第三行到最后（list数据）
        //循环一个vo 就是一行8列
        //创建行
        row = st.createRow(rowIndex++);
        //设置行高
        row.setHeightInPoints(26);
        //创建单元格
        cell = row.createCell(1);
        //给单元格内容
        cell.setCellValue(finance.getFinanceId());
        //给单元格样式
        cell.setCellStyle(text(wb));

        //创建单元格
        cell = row.createCell(2);
        //给单元格内容
        cell.setCellValue(finance.getInputDate());
        //给单元格样式
        cell.setCellStyle(text(wb));

        //创建单元格
        cell = row.createCell(3);
        //给单元格内容
        cell.setCellValue(finance.getInvoiceId());
        //给单元格样式
        cell.setCellStyle(text(wb));

        //创建单元格
        cell = row.createCell(4);
        //给单元格内容
        cell.setCellValue(finance.getInvoiceMoney());
        //给单元格样式
        cell.setCellStyle(text(wb));

        //创建单元格
        cell = row.createCell(5);
        //给单元格内容
        cell.setCellValue(finance.getInvoiceTime());
        //给单元格样式
        cell.setCellStyle(text(wb));

        //创建单元格
        cell = row.createCell(6);
        //给单元格内容
        cell.setCellValue(finance.getExportNos());
        //给单元格样式
        cell.setCellStyle(text(wb));

        //创建单元格
        cell = row.createCell(7);
        //给单元格内容
        cell.setCellValue(finance.getShipmentPort());
        //给单元格样式
        cell.setCellStyle(text(wb));

        //创建单元格
        cell = row.createCell(8);
        //给单元格内容
        cell.setCellValue(finance.getDestinationPort());
        //给单元格样式
        cell.setCellStyle(text(wb));

        //创建单元格
        cell = row.createCell(9);
        //给单元格内容
        cell.setCellValue(finance.getConsignee());
        //给单元格样式
        cell.setCellStyle(text(wb));

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        DownloadUtil downloadUtil = new DownloadUtil();
        wb.write(byteArrayOutputStream);
        downloadUtil.download(byteArrayOutputStream, response, "手写模拟.xlsx");
    }

    //大标题的样式
    public CellStyle bigTitle(Workbook wb) {
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 16);
        font.setBold(true);//字体加粗
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);                //横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);        //纵向居中
        return style;
    }

    //小标题的样式
    public CellStyle title(Workbook wb) {
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("黑体");
        font.setFontHeightInPoints((short) 12);
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);                //横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);        //纵向居中
        style.setBorderTop(BorderStyle.THIN);                        //上细线
        style.setBorderBottom(BorderStyle.THIN);                    //下细线
        style.setBorderLeft(BorderStyle.THIN);                        //左细线
        style.setBorderRight(BorderStyle.THIN);                        //右细线
        return style;
    }

    //文字样式
    public CellStyle text(Workbook wb) {
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("Times New Roman");
        font.setFontHeightInPoints((short) 10);

        style.setFont(font);

        style.setAlignment(HorizontalAlignment.LEFT);                //横向居左
        style.setVerticalAlignment(VerticalAlignment.CENTER);        //纵向居中
        style.setBorderTop(BorderStyle.THIN);                        //上细线
        style.setBorderBottom(BorderStyle.THIN);                    //下细线
        style.setBorderLeft(BorderStyle.THIN);                        //左细线
        style.setBorderRight(BorderStyle.THIN);                        //右细线

        return style;
    }


    @RequestMapping(name = "到出货表页面（excel模板方式--掌握）", value = "/printTemplatepdf")
    public void printTemplatepdf(String packingId) throws Exception {
        //1 根据船期获取到excel需要的数据
        Finance finance = financeService.findById(packingId);
        ;
        //2 将数据填充到准备好的模板中
        ServletContext servletContext = session.getServletContext();
        String path = servletContext.getRealPath("/make/xlsprint/tFINANCE.xls");
        FileInputStream fileInputStream = new FileInputStream(path);
        //读取指定路径的excel工作薄
        Workbook wb = new HSSFWorkbook(fileInputStream);
        Sheet st = wb.getSheetAt(0);

        //逐行注入
        st.getRow(1).getCell(3).setCellValue(finance.getInputDate());
        st.getRow(1).getCell(15).setCellValue(finance.getInvoiceId());
        st.getRow(2).getCell(4).setCellValue(finance.getExportNos());
        st.getRow(3).getCell(3).setCellValue(finance.getConsignee());
        st.getRow(4).getCell(2).setCellValue(finance.getShipmentPort());
        st.getRow(4).getCell(5).setCellValue(finance.getDestinationPort());
        //查询数据
        Packing packing = packingService.findById(finance.getInvoiceId());
        int sum = 7;
        Export export = null;
        if (packing != null) {
            String[] split = packing.getExportNos().split(" ");
            if (split != null) {
                for (int i = 0; i < split.length; i++) {
                    export = exportService.findById(split[i]);
                    if (export != null) {
                        ExportProductExample exportProductExample = new ExportProductExample();
                        ExportProductExample.Criteria criteria = exportProductExample.createCriteria();
                        criteria.andExportIdEqualTo(split[i]);
                        List<ExportProduct> ep = exportProductService.findProductExampleId(exportProductExample);
                        Row row = st.getRow(sum);
                        for (ExportProduct exportProduct : ep) {
                            row.getCell(1).setCellValue(exportProduct.getProductNo());
                            row.getCell(4).setCellValue(exportProduct.getFactoryName());
                            row.getCell(5).setCellValue(exportProduct.getPackingUnit());
                            row.getCell(6).setCellValue(exportProduct.getCnumber());
                            row.getCell(7).setCellValue(exportProduct.getBoxNum());

                            row.getCell(8).setCellValue(export.getGrossWeights());
                            row.getCell(9).setCellValue(export.getMeasurements() - export.getGrossWeights());
                            row.getCell(10).setCellValue(exportProduct.getSizeHeight());
                            row.getCell(11).setCellValue(exportProduct.getSizeWidth());
                            row.getCell(12).setCellValue(exportProduct.getSizeLength());
                            row.getCell(13).setCellValue(exportProduct.getPrice());
                            row.getCell(14).setCellValue(exportProduct.getExPrice());
                            row.getCell(15).setCellValue(exportProduct.getTax());
                            row.getCell(16).setCellValue(exportProduct.getPrice());
                            double v = exportProduct.getPrice() * 0.3;
                            row.getCell(17).setCellValue(v);
                            sum++;
                        }
                    }
                }
            }
        }
        //导成表
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        DownloadUtil downloadUtil = new DownloadUtil();
        wb.write(byteArrayOutputStream);
        downloadUtil.download(byteArrayOutputStream, response, "111.xls");
    }
}
